const Koa = require('koa');
const path = require('path');
const logger = require('koa-logger');
const koaBody = require('koa-body');
const onerror = require('koa-onerror');
const koaStatic = require('koa-static');
const favicon = require('koa-favicon');

const views = require('./rest/middlewares/koa-njk');
const {static_path} = require('./config/index');
const router = require('./rest/routes/index');

const is_production = process.env.NODE_ENV === 'production';

const app = new Koa();

// 统一错误处理
onerror(app);

// 解析body
app.use(koaBody());

app.use(logger());

//跨域处理
app.use(async (ctx, next) => {
  ctx.response.set({
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS'
  });

  await next();
});

app.use(favicon(__dirname + '/public/favicon.ico'));
//静态资源路径,生产环境添加缓存
if (is_production) {
  app.use(koaStatic(path.join(__dirname), {
    maxage: 10 * 24 * 60 * 60 * 1000
  }));
} else {
  app.use(koaStatic(path.join(__dirname)));
}
// 应用njk模板引擎
app.use(views('./views', {
  noCache: !is_production,
  watch: !is_production
})
);

app.use(router.routes());

app.use(function(ctx) {
  ctx.render('error.html', {error: ctx.response});
});

module.exports = app;